package cn.gzjp.modules.gas.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaCodeLineColor;
import cn.gzjp.common.config.Global;
import cn.gzjp.modules.gas.service.GasWxService;
import cn.hutool.core.io.FileUtil;
import me.chanjar.weixin.common.exception.WxErrorException;
import org.apache.commons.io.FilenameUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import cn.gzjp.common.utils.DateUtils;
import cn.gzjp.common.utils.MyBeanUtils;
import cn.gzjp.common.persistence.Page;
import cn.gzjp.common.web.BaseController;
import cn.gzjp.common.utils.StringUtils;
import cn.gzjp.common.utils.excel.ExportExcel;
import cn.gzjp.common.utils.excel.ImportExcel;
import cn.gzjp.modules.gas.entity.GasGun;
import cn.gzjp.modules.gas.service.GasGunService;

/**
 * 加油站油枪Controller
 * @author zengcp
 * @version 2018-03-05
 */
@Controller
@RequestMapping(value = "${adminPath}/gas/gasGun")
public class GasGunController extends BaseController {

	@Autowired
	private GasGunService gasGunService;

	WxMaService wxService = GasWxService.getWxMaService();
	
	
	/**
	 * 加油站油枪列表页面
	 */
	@RequiresPermissions("gas:gasGun:list")
	@RequestMapping(value = {"list", ""})
	public String list(GasGun gasGun, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<GasGun> page = gasGunService.findPage(new Page<GasGun>(request, response), gasGun); 
		model.addAttribute("page", page);
		return "modules/gas/gasGunList";
	}

	/**
	 * 查看，增加，编辑加油站油枪表单页面
	 */
	@RequiresPermissions(value={"gas:gasGun:view","gas:gasGun:add","gas:gasGun:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(GasGun gasGun, Model model) {
		model.addAttribute("gasGun", gasGun);
		return "modules/gas/gasGunForm";
	}

	/**
	 * 保存加油站油枪
	 */
	@RequiresPermissions(value={"gas:gasGun:add","gas:gasGun:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(GasGun gasGun, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, gasGun)){
			return form(gasGun, model);
		}
		if(!gasGun.getIsNewRecord()){//编辑表单保存
			GasGun t = gasGunService.get(gasGun.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(gasGun, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			gasGunService.save(t);//保存
		}else{//新增表单保存
			gasGunService.save(gasGun);//保存
		}
		addMessage(redirectAttributes, "保存加油站油枪成功");
		return redirect("/gas/gasGun/?repage");
	}

	/**
	 * 创建二维码
	 */
	@RequestMapping(value = "createCode")
	public String createCode(String id, RedirectAttributes redirectAttributes) {
		try {
			File file = wxService.getQrcodeService().createWxCodeLimit(id, "pages/zhjy/zhjy", 430, false, new WxMaCodeLineColor("0","0","0"));
			String extension = FilenameUtils.getExtension(file.getName());
			String savePath = "/userfiles/qrcode/"+id+"."+extension;
			String pathname = Global.getFileUploadPath() + savePath;

			File outPutFile = new File(pathname);
			FileUtil.copy(file,outPutFile,true);
			GasGun gasGun = gasGunService.get(id);
			gasGun.setQrcodePath(savePath);
			gasGunService.save(gasGun);
		} catch (WxErrorException e) {
			e.printStackTrace();
		}

		addMessage(redirectAttributes, "创建二维码成功");
		return redirect("/gas/gasGun/?repage");
	}


	/**
	 * 删除加油站油枪
	 */
	@RequiresPermissions("gas:gasGun:del")
	@RequestMapping(value = "delete")
	public String delete(GasGun gasGun, RedirectAttributes redirectAttributes) {
		gasGunService.delete(gasGun);
		addMessage(redirectAttributes, "删除加油站油枪成功");
		return redirect("/gas/gasGun/?repage");
	}
	
	/**
	 * 批量删除加油站油枪
	 */
	@RequiresPermissions("gas:gasGun:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			gasGunService.delete(gasGunService.get(id));
		}
		addMessage(redirectAttributes, "删除加油站油枪成功");
		return redirect("/gas/gasGun/?repage");
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("gas:gasGun:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(GasGun gasGun, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "加油站油枪"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<GasGun> page = gasGunService.findPage(new Page<GasGun>(request, response, -1), gasGun);
    		new ExportExcel("加油站油枪", GasGun.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出加油站油枪记录失败！失败信息："+e.getMessage());
		}
		return redirect("/gas/gasGun/?repage");
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("gas:gasGun:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<GasGun> list = ei.getDataList(GasGun.class);
			for (GasGun gasGun : list){
				try{
					gasGunService.save(gasGun);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条加油站油枪记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条加油站油枪记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入加油站油枪失败！失败信息："+e.getMessage());
		}
		return redirect("/gas/gasGun/?repage");
    }
	
	/**
	 * 下载导入加油站油枪数据模板
	 */
	@RequiresPermissions("gas:gasGun:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "加油站油枪数据导入模板.xlsx";
    		List<GasGun> list = Lists.newArrayList(); 
    		new ExportExcel("加油站油枪数据", GasGun.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return redirect("/gas/gasGun/?repage");
    }
	@ModelAttribute
	public GasGun get(@RequestParam(required=false) String id) {
		GasGun entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = gasGunService.get(id);
		}
		if (entity == null){
			entity = new GasGun();
		}
		return entity;
	}
	

}